package com.kajespero.webapp.validator.annotation.process;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kajespero.vo.VO;
import com.kajespero.webapp.validator.annotation.Validator;
import com.kajespero.webapp.validator.commons.IValidator;

public class ValidatorAnnotationProcess {
	
	private static final Log LOG = LogFactory.getLog(ValidatorAnnotationProcess.class);
	
	public static <T extends VO> boolean process(T instance){
		IValidator<T> validator = getValidator(instance);
		if(validator != null){
			return validator.valid(instance);
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends VO> IValidator<T> getValidator(T instance){
		Validator validator = instance.getClass().getAnnotation(Validator.class);
		if(validator != null){
			Class<?> validatorClass = validator.clazz();
			try {
				return (IValidator<T>) validatorClass.newInstance();
			} catch (InstantiationException e) {
				LOG.error("InstantiationException " + e.getMessage(), e);
			} catch (IllegalAccessException e) {
				LOG.error("IllegalAccessException " + e.getMessage(), e);
			}
		}
		return null;
	}

}
